import { Cell, Graph } from "@antv/x6";
// import { postAddMapZone, postUpdateMapZone } from "@/api/map";
import { filterKey } from "@/utils/index";

import { useToolStore } from "@/store/modules/tools";
// import { useCanvansMapStore } from "@/store/modules/canvansMap";
const toolStore = useToolStore();
// const canvansMapStore = useCanvansMapStore();
const toolType = computed(() => toolStore.toolType);

type ClickData = {
  x: number;
  y: number;
  clientX: number;
  clientY: number;
};

type size = {
  width: number;
  height: number;
};

// 缓存动态拉伸节点尺寸
let tempSize: size = {
  width: 0,
  height: 0,
};

let areaNode: Cell | any = null;

// 移动缓存坐标信息
const downData: ClickData = {
  x: 0,
  y: 0,
  clientX: 0,
  clientY: 0,
};

// 节点起始坐标
const position = {
  x: 0,
  y: 0,
};

// 最小区域尺寸，
const miniSize: number = 16;

// 获取最新元素计数，每次返回当前元素中最大id
function getMaxId(graph: Graph) {
  const nodeList = graph.getCells().filter((item: any) => item.shape === "node-area");
  const ids = nodeList.map((item: { id: string }) => {
    if (item.id.startsWith("r") && item.id.length < 10) {
      // 过滤非法节点id及默认自动生成带有相关字符的id
      return Number(item.id.replace("r", ""));
    } else {
      return 0;
    }
  });
  return ids.length ? Math.max(...ids) + 1 : 1;
}

let isInit = false;
// 绘制功能区域
export const drawArea = (graph: Graph) => {
  if (isInit === false) {
    graph.on("blank:mousedown", ({ x, y, e }) => {
      if (toolType.value !== "area") return;
      isInit = true;
      Object.assign(position, { x, y });
      Object.assign(downData, { x, y, clientX: e.clientX, clientY: e.clientY });
      const nodeId = getMaxId(graph);
      areaNode = graph.addNode({
        id: `r${nodeId}`,
        shape: "node-area",
        zIndex: -1,
        x,
        y,
        data: {
          zoneNameEn: `r${nodeId}`,
          zoneName: `区域${nodeId}`,
          points: [],
          tempSize,
        },
      });
    });
  }
  graph.on("blank:mouseup", ({ x, y }) => {
    if (toolType.value !== "area") return;
    if (tempSize.width < miniSize || tempSize.height < miniSize) {
      graph.removeNode(areaNode);
    } else {
      const data = areaNode.getData();
      const position = areaNode.position();
      const size = areaNode.size();

      data.points.push(position);
      data.points.push({
        x: position.x + size.width,
        y: position.y,
      });
      data.points.push({
        x: position.x,
        y: position.y + size.height,
      });
      data.points.push({
        x: position.x + size.width,
        y: position.y + size.height,
      });
      areaNode.setData(data);
    }
    tempSize = {
      width: 0,
      height: 0,
    };
  });
  graph.on("blank:mousemove", ({ x, y, e }) => {
    if (toolType.value !== "area") return;
    if ((downData.x < 0 && x < 0) || (downData.x > 0 && x > 0)) {
      tempSize.width = Number(Math.abs(downData.x - x).toFixed(0));
    } else {
      tempSize.width = Math.abs(downData.x) + Math.abs(x);
    }

    if ((downData.y < 0 && y < 0) || (downData.y > 0 && y > 0)) {
      tempSize.height = Number(Math.abs(downData.y - y).toFixed(0));
    } else {
      tempSize.height = Math.abs(downData.y) + Math.abs(y);
    }
    downData.clientX > e.clientX && (position.x = x);
    downData.clientY > e.clientY && (position.y = y);
    areaNode.position(position.x, position.y);
    areaNode.size(tempSize.width, tempSize.height);
    areaNode.setData({
      tempSize,
    });
  });
  graph.bindKey("Escape", () => {
    toolStore.changeTool("");
  });
};

// 根据坐标值计算宽高
export const computedSize = (points: Array<{ x: number; y: number }>): { width: number; height: number } => {
  const xArr: number[] = [];
  const yArr: number[] = [];
  points.forEach((item: any) => {
    xArr.push(item.x);
    yArr.push(item.y);
  });
  const minX = Math.min(...xArr);
  const maxX = Math.max(...xArr);
  const minY = Math.min(...yArr);
  const maxY = Math.max(...yArr);
  const size = {
    width: maxX - minX,
    height: maxY - minY,
  };
  return size;
};

// 更新区域坐标点位(宽高)
export const updateAreaPoint = (node: Cell) => {
  const nodeData = node.getData();
  const position = node.getProp("position");
  const nodeSize = computedSize(nodeData.points);
  const points: Array<{ x: number; y: number }> = [];
  points.push(position);
  points.push({
    x: position.x + nodeSize.width,
    y: position.y,
  });
  points.push({
    x: position.x,
    y: position.y + nodeSize.height,
  });
  points.push({
    x: position.x + nodeSize.width,
    y: position.y + nodeSize.height,
  });
  nodeData.points = points;

  // const data = filterKey(JSON.parse(JSON.stringify(nodeData)))
  // if(!data.deviceId || data.deviceId === -1) {
  //   ElMessage.warning('请设置功能区域必填项')
  // }else{
  //   // postUpdateMapZone(data).then((res:any) => {
  //   //   ElMessage.success('操作成功')
  //   //   node.setData({
  //   //     ...nodeData,
  //   //     tempSize: nodeSize
  //   //   })
  //   // })
  // }
};

// 
export const handleArea = () => {
  
}
